const express = require('express')
const cors = require('cors')
const { port, secret, error } = require('./config')
const colors = require('colors')
const { log, wrap } = require('./tool')
const SMTPPool = require('nodemailer/lib/smtp-pool')
const jwt = require('jsonwebtoken')
const R = /(?<=Bearer )\S+/i

const app = express()

// 解决跨域
app.use(cors())

// 静态托管
app.use(express.static('./public', {
   extensions: ['html'],
   index: 'index.html'
}))
// 解决post请求参数
app.use(express.urlencoded({ extended: false, limit: 1024 * 1024 }))
app.use(express.json())
app.use((req, res, next) => {
   console.log('='.repeat(80).red);
   const { body } = req
   let arr = []
   for (const k in body) {
      let v = body[k].slice(0, 30)
      arr.push(k + ': ' + v)
   }
   log('发起请求', {
      ip: req.ip.replace(/f|:/g, ''),
      method: req.method,
      url: req.path,
      param: '{' + arr.join(', ') + '}',
      'Content-Type': req.headers['content-type']
   }, true)
   next()
})

// 用户验证
app.use(wrap(async (req, res, next) => {
   const { authorization } = req.headers
   if (!authorization) {
      req.userq = '401'
      next()
      return
   }
   const q = R.exec(authorization)
   if (!q) {
      req.userq = '401'
      next()
      return
   }
   const token = q[0]
   if (!token) {
      req.userq = '401'
      next()
      return
   }
   try {
      const data = jwt.verify(token, secret)
      req.user = data.data
   } catch (error) {
      req.userq = '402'
      next()
      return
   }
   log('用户验证', {
      User: JSON.stringify(req.user)
   });
   next()
}))

// 登陆
app.use(require('./route/login'))

// 注册
app.use(require('./route/register'))

// 发送验证码
app.use(require('./route/authcode'))

// 用户验证
app.use('/api', require('./api'))

// 其他
app.use(require('./route'))

// 统一处理错误
app.use((req, res, next) => {
   res.send({
      code: 404,
      msg: '找不到资源'
   })
})
app.use((err, req, res, next) => {
   const code = err
   const msg = error[code]
   if (msg) return res.send({
      code: +code,
      msg
   })
   res.send({ code: 500, msg: error[500] })
   console.log(err);
})

app.listen(port, () => {
   console.log(`server running ... address: http://127.0.0.1:${port}`)
})